package wiki.generic.concretebar;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import wiki.generic.bar.BarLink;
import wiki.generic.bar.SideBar;
import wiki.generic.io.SideBarLinksReader;
import wiki.generic.med.BarService;
import wiki.generic.utilities.Substring;
/**
 * 
 * @author <p><strong>JwTeam</strong></p> 
 *
 */
public class ConcreteLinksReader implements SideBarLinksReader {

	private String filePath;
	private BarService bs;

	public ConcreteLinksReader(String filePath, BarService bs) {
		super();
		this.filePath = filePath;
		this.bs=bs;
	}

	public SideBar getBar(String filep) {
		File file = new File(filep);
		HashMap<String, List<BarLink>> map = new HashMap<String, List<BarLink>>();
		List<String> categories=new ArrayList<String>();
		try {
			BufferedReader reader = new BufferedReader(new FileReader(file));
			String s = reader.readLine();
			while (s != null) {
				List<BarLink> linksList= new ArrayList<BarLink>();
				putIn(s, map, linksList,categories);
				s = reader.readLine();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return new ConcreteSideBar(map, categories);
	}

	
	
	
	private void putIn(String s,HashMap<String, List<BarLink>> map, List<BarLink> linksList, List<String> categories){

		Substring sub=new Substring(s, "$$||$$");
		String categoria= sub.nextSubString();
		categories.add(categoria);
		while(sub.hasMore()){
			String nome=sub.nextSubString();
			String URL=sub.nextSubString();
			linksList.add(bs.generateLink(nome, URL));
		}
		map.put(categoria, linksList);	
	}
	
	@Override
	public String getFile() {
		return filePath;
	}


	@Override
	public HashMap<String, SideBar> getSideBar(HashMap<String, String> courses) {
		
		Set<String> keys=courses.keySet();
		HashMap<String, SideBar> bmap=new HashMap<String, SideBar>();
		for (Iterator<String> iterator = keys.iterator(); iterator.hasNext();) {
			String corso = iterator.next();
			String path=courses.get(corso)+"/"+filePath;
			SideBar bar=getBar(path);
			bmap.put(corso, bar);	
		}	
		return bmap;
	}
}
